package com.giga.controller;

import com.giga.entity.Email;
import com.giga.entity.User;
import com.giga.service.UserService;
import com.giga.service.impl.MailService;
import com.giga.utils.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private MailService mailService;

    /**
     * 后台发送页面
     */
    @RequestMapping("/login")
    public Object login() {
//        List<User> users = userService.selectAll();
        ModelAndView mv = new ModelAndView();
//        mv.addObject("users", users);
        mv.setViewName("bs/login");
        return mv;
    }

    /**
     * 邮件多人发送文字及图片
     */
    @RequestMapping("/send")
    @ResponseBody
    public int send(Email email, @RequestParam(value = "file_image", required = false) MultipartFile multipartFile) throws MessagingException {
        List<User> users = userService.selectAll();
        List<String> emails = new ArrayList<>();
        for (User user : users) emails.add(user.getEmail());

        String[] to = emails.toArray(new String[0]);
        // 调用utils层的方法进行文件上传处理进行查询操作
        if (multipartFile.isEmpty()) {
            mailService.sendSimpleTextMail(to, email.getSubject(), email.getContent());
        } else {
            String imgPath = MyUtils.doSingleFileUpload1(multipartFile, "sendInfoFile", "sendInfo-", email, "image");

            String content =
                    "<br/><img src='cid:test001'>";
//            mailService.sendImgSingle(to, email.getSubject(), email.getContent() + content, "target/classes/static/sendInfoFile/" + imgPath, "test001");
            mailService.sendImgSingle(to, email.getSubject(), email.getContent() + content, "sendInfoFile/" + imgPath, "test001");
        }
        return 1;
    }

}
